package com.strongbj.iot.devices.zebra.fx7500.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class Fx7500ClientService implements ApplicationListener<ApplicationEvent> {
	private static Map<String,Fx7500Client> clients = new HashMap<String, Fx7500Client>();
	private static List<DoorConfig> doorConfigList=new ArrayList<DoorConfig>();
	
	/**
	 * 获取所有连接的客户端
	 * @return
	 */
	public static Map<String,Fx7500Client> getClients(){
		return clients;
	}
	
	public static List<DoorConfig> getConfig(){
		return doorConfigList;
	}
	
	public static void runNewClient(DoorConfig dc){
		Fx7500Client client = new Fx7500Client();
		client.connectToReader(dc.getIp(), 5084);
		client.startRead();
		clients.put(dc.getIp(),client);
	}
	
	public void setDoorConfig(String doorConfig) {
		String[] dcs = doorConfig.split(";");

		for(String dc : dcs){
			String[] d = dc.split(":");
			DoorConfig _dc = new DoorConfig();
			_dc.setIp(d[0]);
			_dc.setDirection(d[1]);
			doorConfigList.add(_dc);
		}
		
	}

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		for(DoorConfig dc:doorConfigList){
			runNewClient(dc);
		}
	}
	
	public static Fx7500Client getClient(String ip){
		return clients.get(ip);
	}
}
